Simple JDBC implementation

chris (2003-07-06 22:43:57)
3327 views
0 replies
Well it's my first time playing with JDBC and I have got a simple script working. It uses the J/connect mysql JDBC driver and runs a simple select statement and prints the 2 columns onto the screen.

I'm still finding that the most fiddly thing with Java is sorting out the environment - i.e. setting the CLASSPATH and making sure that any requred JAR files are within it.. it can be quite muddling.

Anyway, Here's the source code from today's simple experiment:


import java.lang.*;
import java.net.*;
import java.sql.*;
import com.mysql.jdbc.Driver;

class DBTalker{
	public static void main(String args[]){
		try{
			Class.forName("com.mysql.jdbc.Driver");
		}
		catch (java.lang.ClassNotFoundException e) {
			System.err.print("ClassNotFoundException: ");
			System.err.println(e.getMessage());
		}

		Connection con;
		String query = "SELECT ha_surname, ha_firstname from handles";
		Statement stmt;
	
		String url="jdbc:mysql://10.0.0.45/g1?user=username&password=password";

		try {
			System.out.println("Connecting to db server...");	
			
			con = DriverManager.getConnection(url);
			
                	System.out.println("connected!");
			stmt = con.createStatement();
			ResultSet result = stmt.executeQuery(query);
			while (result.next()) {
				String name = result.getString(1) + " " + result.getString(2);
				System.out.println(name);
			}	
			stmt.close();
			con.close();
		}
		catch(SQLException ex) {
			System.err.print("SQLException: ");
			System.err.println(ex.getMessage());
		}		
	}			
}

christo
comment